package com.jweb.framework.security;

import java.io.IOException;
import java.io.InputStream;
import java.io.Reader;
import java.util.Iterator;
import java.util.Properties;
import java.util.Set;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.DefaultPropertiesPersister;

import com.jweb.framework.security.pass.IDecryptPass;
import com.jweb.framework.security.pass.PassFac;

/**
 * 修改人： Thomas
 * 修改内容：新增 
 * 类说明：密码属性字段解密
 */
public class PwdPropertiesPersister extends DefaultPropertiesPersister {
	
	private static Logger logger = LoggerFactory.getLogger(PwdPropertiesPersister.class);
	
	public void load(Properties properties , InputStream inputStream) throws IOException {
		super.load(properties , inputStream);
		transform(properties);
	}
	
	public void load(Properties properties , Reader reader) throws IOException {
		super.load(properties, reader);
		transform(properties);
	}
	
	private void transform(Properties properties) {
		Set set = properties.keySet() ;
		for(Iterator it = set.iterator() ; it.hasNext() ;){
			Object obj = it.next() ;
			String s = properties.getProperty(obj.toString());
			if(s.startsWith("&{") && s.endsWith("}")){
				String s1 = s.substring(2 , s.length() - 1);
				String as[] = s1.split(":");
				if(as.length != 2){
					logger.error("Resolve password error . Password replacement must be in format &{hostIP:accoutntName}.");
				}
				else {
					String hostIp = as[0];
					String accountName = as[1];
					logger.debug((new StringBuilder("Resolve password,hostIP = [")).append(hostIp).append("] accountName =[").append(accountName).append("]").toString());
					IDecryptPass idecryptpass = PassFac.getDecryptPass();
					try {
						String passwd = idecryptpass.getDePass(hostIp, accountName);
						properties.setProperty(obj.toString(), passwd);
					} catch (Exception e) {
						logger.error("Resolve password error . " , e);
					}
				}
			}
		}
	}
	
}
